package com.example.luyennghe;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class RegisterActivity extends Activity {
    private EditText edtUsername;
    private EditText edtPassword;
    private EditText edtEmail;
    private EditText edtHoten;
    private EditText edtGioitinh;
    private EditText edtNgaysinh;
    private ImageButton imgbtnRegister;
    private ProgressDialog pDialog;
    private String ngaydangky;  
    private UserInfo user = new UserInfo();
    
    private String urlRegister = "http://huynh.cu.cc/android-server/register.php";
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
    private JSONParser jParser = new JSONParser();
    private boolean register_Success = false;
    private boolean register_InsertFail = false;
    private boolean register_UsernameExists = false;
    private boolean register_ErrorConnect = false;
    
    private static final String TAG_USERNAME = "username";
    private static final String TAG_PASSWORD = "password";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_HOTEN = "hoten";
    private static final String TAG_NGAYSINH = "ngaysinh";
    private static final String TAG_NGAYDANGKY = "ngaydangky";
    private static final String TAG_GIOITINH = "gioitinh";
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_layout);
        edtUsername = (EditText)findViewById(R.id.edtUsername);
        edtPassword = (EditText)findViewById(R.id.edtPassword);
        edtEmail = (EditText)findViewById(R.id.edtEmail);
        edtHoten = (EditText)findViewById(R.id.edtHoten);
        edtGioitinh = (EditText)findViewById(R.id.edtGioitinh);
        edtNgaysinh = (EditText)findViewById(R.id.edtNgaysinh);
        imgbtnRegister = (ImageButton)findViewById(R.id.imgbtnRegister);
        imgbtnRegister.setOnClickListener(registerAccount);
        edtEmail.setOnFocusChangeListener(new OnFocusChangeListener() {
            
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                // TODO Auto-generated method stub
                if(!hasFocus){
                    if(!isEmailValid(edtEmail.getText().toString())){
                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                RegisterActivity.this);
                        builder.setTitle("Lỗi")
                                .setMessage("Email không đúng định dạng.")
                                .setCancelable(false)
                                .setIcon(R.drawable.warning_icon)
                                .setPositiveButton("OK",
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                    int id) {
                                                dialog.dismiss();
                                                edtEmail.requestFocus();
                                            }
                                        });
                        AlertDialog alert = builder.create();
                        alert.show();
                    }
                }
            }
        });
        edtPassword.setOnFocusChangeListener(new OnFocusChangeListener() {
            
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                // TODO Auto-generated method stub
                if(!hasFocus){
                    if(edtPassword.getText().toString().length() < 6){
                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                RegisterActivity.this);
                        builder.setTitle("Lỗi")
                                .setMessage("Password phải nhiều hơn 6 kí tự.")
                                .setCancelable(false)
                                .setIcon(R.drawable.warning_icon)
                                .setPositiveButton("OK",
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                    int id) {
                                                dialog.dismiss();
                                                edtPassword.setText("");
                                            }
                                        });
                        AlertDialog alert = builder.create();
                        alert.show();
                    }
                }
            }
        });
        Calendar c1 = Calendar.getInstance();      
        ngaydangky = String.valueOf(c1.get(Calendar.DAY_OF_MONTH))+ "/" + String.valueOf(c1.get(Calendar.MONTH)) +"/" + String.valueOf(c1.get(Calendar.YEAR));
        
    }
    public static boolean isEmailValid(String email) {
        boolean isValid = false;

        String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
        CharSequence inputStr = email;

        Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }
    View.OnClickListener registerAccount = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(!checkInternetConnection()){
                if(edtEmail.getText().toString().equals("")||edtGioitinh.getText().toString().equals("")
                        ||edtHoten.getText().toString().equals("")||edtNgaysinh.getText().toString().equals("")
                        ||edtPassword.getText().toString().equals("")||edtUsername.getText().toString().equals("")){
                    AlertDialog.Builder builder = new AlertDialog.Builder(
                            RegisterActivity.this);
                    builder.setTitle("Lỗi")
                            .setMessage("Đề nghị nhập đầy đủ thông tin.")
                            .setCancelable(false)
                            .setIcon(R.drawable.warning_icon)
                            .setPositiveButton("OK",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog,
                                                int id) {
                                            dialog.dismiss();
                                        }
                                    });
                    AlertDialog alert = builder.create();
                    alert.show();
                }
                else
                {
                    user.setEmail(edtEmail.getText().toString());
                    user.setGioiTinh(edtGioitinh.getText().toString());
                    user.setHoTen(edtHoten.getText().toString());
                    user.setNgayDangKy(ngaydangky);
                    user.setNgaySinh(edtNgaysinh.getText().toString());
                    user.setPassword(edtPassword.getText().toString());
                    user.setUsername(edtUsername.getText().toString());
                    //gui thong tin dang ky
                    registerHandler();
                }
            }
            else{
                Toast.makeText(getApplicationContext(), "Không có kết nối internet. Xin hãy thử lại", Toast.LENGTH_SHORT).show();
            }
        }
    };  
    class RegisterAccount extends AsyncTask<String, String, String> {
         
        @Override
        protected void onPreExecute() {
            super.onPreExecute();      
            pDialog = new ProgressDialog(RegisterActivity.this);
            pDialog.setMessage("Đang kết nối đến server. Vui lòng đợi...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 
        protected String doInBackground(String... args) {
            // Building Parameters            
            List<NameValuePair> paramsRegister = new ArrayList<NameValuePair>();
            paramsRegister.add(new BasicNameValuePair(TAG_USERNAME, user.getUsername()));   
            paramsRegister.add(new BasicNameValuePair(TAG_PASSWORD, user.getPassword())); 
            paramsRegister.add(new BasicNameValuePair(TAG_HOTEN, user.getHoTen()));
            paramsRegister.add(new BasicNameValuePair(TAG_EMAIL, user.getEmail()));
            paramsRegister.add(new BasicNameValuePair(TAG_GIOITINH, user.getGioiTinh()));
            paramsRegister.add(new BasicNameValuePair(TAG_NGAYSINH, user.getNgaySinh()));
            paramsRegister.add(new BasicNameValuePair(TAG_NGAYDANGKY, user.getNgayDangKy()));
            JSONObject json = new JSONObject();
            // getting JSON string from URL
            try {               
                //gui du lieu len server
                json = jParser.makeHttpRequest(urlRegister, "POST",
                        paramsRegister);
                Log.d("login: ", json.toString());
                // Check SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
                String mes = json.getString(TAG_MESSAGE);
                if (success == 1 && mes.equals("OK")) {
                    register_Success = true;                    
                }
                else
                {
                    if(success==0 && mes.equals("Can't insert into database")){
                        register_InsertFail = true;
                    }
                    else
                    {
                        if(success==0 &&  mes.equals("Username already exists")){
                            register_UsernameExists = true;
                        }
                        else
                        {
                            register_ErrorConnect = true;
                        }
                    }
                }
                    
            } 
            catch (Exception ex) {
                Toast.makeText(getApplicationContext(), "Có lỗi xảy ra. " + ex.toString(), Toast.LENGTH_SHORT).show();
                finish();
            }
            return null;
        }
         
        protected void onPostExecute(String file_url) {
            // updating UI from Background Thread
            pDialog.dismiss();
            if(register_Success){     
                register_Success = false;
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        RegisterActivity.this);
                builder.setTitle("Chúc mừng")
                        .setMessage("Bạn đã đăng ký tài khoản thành công.")
                        .setCancelable(false)
                        .setIcon(R.drawable.warning_icon)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int id) {
                                        dialog.dismiss();
                                        finish();
                                        Intent in = new Intent(getApplicationContext(), MainActivity.class);
                                        in.putExtra("userinfo", user);              
                                        startActivity(in);
                                    }
                                });
                AlertDialog alert = builder.create();
                alert.show();
            }
            else
                if(register_InsertFail) 
                {
                    register_InsertFail = false;
                    AlertDialog.Builder builder = new AlertDialog.Builder(
                            RegisterActivity.this);
                    builder.setTitle("Lỗi")
                            .setMessage("Không thể kết nối đến database. Hãy thử lại sau.")
                            .setCancelable(false)
                            .setIcon(R.drawable.warning_icon)
                            .setPositiveButton("OK",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog,
                                                int id) {
                                            dialog.dismiss();
                                        }
                                    });
                    AlertDialog alert = builder.create();
                    alert.show();
                }
                else
                    if(register_UsernameExists){
                        register_UsernameExists = false;
                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                RegisterActivity.this);
                        builder.setTitle("Lỗi")
                                .setMessage("Tên tài khoản đã có người sử dụng. Vui lòng chọn tên khác.")
                                .setCancelable(false)
                                .setIcon(R.drawable.warning_icon)
                                .setPositiveButton("OK",
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                    int id) {
                                                dialog.dismiss();
                                                edtUsername.requestFocus();
                                            }
                                        });
                        AlertDialog alert = builder.create();
                        alert.show();
                    }
                    else
                        if(register_ErrorConnect){
                            register_ErrorConnect = false;
                            AlertDialog.Builder builder = new AlertDialog.Builder(
                                    RegisterActivity.this);
                            builder.setTitle("Lỗi")
                                    .setMessage("Thông tin không đủ. Hãy thử lại sau.")
                                    .setCancelable(false)
                                    .setIcon(R.drawable.warning_icon)
                                    .setPositiveButton("OK",
                                            new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog,
                                                        int id) {
                                                    dialog.dismiss();
                                                }
                                            });
                            AlertDialog alert = builder.create();
                            alert.show();
                        }
        }
    }
    private boolean checkInternetConnection() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        // kiểm tra kết nối wifi và mobile(3G)
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    return true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    return true;
        }
        if (cm.getActiveNetworkInfo() != null
                && cm.getActiveNetworkInfo().isAvailable()
                && cm.getActiveNetworkInfo().isConnected()) {
            return true;
        }
        return false;
    }
    public void registerHandler(){
        final RegisterAccount rg = new RegisterAccount();
        rg.execute();
        Handler _handler = new Handler();
        _handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (rg.getStatus() == AsyncTask.Status.RUNNING) {
                    rg.cancel(true);
                    pDialog.dismiss();
                    AlertDialog.Builder builder = new AlertDialog.Builder(
                            RegisterActivity.this);
                    builder.setMessage(
                            "Kết nối quá thời gian. Xin hãy thử lại.")
                            .setCancelable(false)
                            .setTitle("Lỗi")
                            .setIcon(R.drawable.warning_icon)
                            .setPositiveButton("OK",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialog, int id) {
                                            dialog.dismiss();
                                        }
                                    });
                    AlertDialog alert = builder.create();
                    alert.show();
                }
            }
        }, 30000); // timeout sau ... giây sẽ hiện thông báo không kết nối được.
    }
}
